/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.headerfooter;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.geom.Dimension2D;

import javax.swing.Icon;

import org.dom4j.Element;

import com.reportgear.core.util.ImageUtils;
import com.reportgear.report.model.cell.style.FontStyle;
import com.reportgear.report.view.grid.util.GraphHelper;

/**
 * 页眉页脚元素-文本
 * 
 * @version 1.0 2011-4-22
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class TextHFElement extends AbstractHFElement {
	protected String text;
	protected FontStyle fontStyle;

	public TextHFElement() {
		this("", FontStyle.DEFAULT_STYLE);
	}

	public TextHFElement(String text, FontStyle fontStyle) {
		this.type = HFElement.TYPE_TEXT;
		this.text = text;
		this.fontStyle = FontStyle.getInstance(fontStyle);
	}

	@Override
	public String getCaption() {
		return "文本";
	}

	@Override
	public Icon getIcon() {
		return ImageUtils.readIcon("/resources/images/dialog/headerfooter/text.png");
	}

	@Override
	public Dimension2D getSize() {
		String[] lines = this.text.split("\n");
		FontMetrics fontMetrics = GraphHelper.getFontMetrics(this.fontStyle);

		int w = 0;
		for (String line : lines) {
			w = Math.max(fontMetrics.stringWidth(line), w);
		}

		return new Dimension(w, fontMetrics.getHeight() * lines.length);
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getText() {
		return text;
	}

	public void setFontStyle(FontStyle fontStyle) {
		this.fontStyle = fontStyle;
	}

	public FontStyle getFontStyle() {
		return fontStyle;
	}

	@Override
	public HFElement read(Element parent) {
		if (parent == null) {
			return this;
		}

		this.text = parent.elementTextTrim("text");
		this.fontStyle = this.fontStyle.read(parent.element("font"));

		return this;
	}

	@Override
	public void write(Element parent) {
		if (parent == null) {
			return;
		}

		Element el;

		el = parent.addElement(HFElement.XML_TAG_TYPE);
		el.addText(this.type);

		el = parent.addElement("text");
		el.addText(text);

		el = parent.addElement("font");
		this.fontStyle.write(el);
	}
}
